//
//  RegisterView.m
//  lv678
//
//  Created by apple on 15/6/17.
//  Copyright (c) 2015年 lampshade. All rights reserved.
//

#import "RegisterView.h"
#import "AFNetworking.h"
#import "ValidateHelper.h"
#import "CityPicker.h"

@interface RegisterView()<CityPickerDelegate>

@property (nonatomic, strong) AFHTTPRequestOperationManager *managers;
@property (nonatomic, strong) UIView *selectBackView;
@property (nonatomic, strong) UIView *cityView;
@property (nonatomic, copy) NSString *province;
@property (nonatomic, copy) NSString *city;
@property (nonatomic, copy) NSString *dis;

@end

NSString *url = nil;
NSString *randomCode = nil;

@implementation RegisterView

- (void)drawRect:(CGRect)rect {
    [self initView];
    
}

#pragma mark - 初始化视图
- (void)initView{
    
    _confirmPsw.delegate      = self;
    _phoneNum.delegate        = self;
    _newsPsw.delegate         = self;
    _identityCode.delegate    = self;
    self.frame                = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height*2);
    
    
    /*通过plist文件获取URL地址*/
    NSString *plistPath       = [[NSBundle mainBundle] pathForResource:@"UrlList" ofType:@"plist"];
    NSMutableDictionary *data = [[NSMutableDictionary alloc]initWithContentsOfFile:plistPath];
    
    url = [data valueForKey:@"memberCenter"];
    
    
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectCityName)];
    recognizer.numberOfTapsRequired = 1;
    [self.selectCity addGestureRecognizer:recognizer];
}

#pragma mark - 实现城市选择器代理
- (void)disappearView{
    [self.selectBackView removeFromSuperview];
    [self.cityView removeFromSuperview];
}


- (void)sendProvince:(NSString *)province sendCity:(NSString *)city sendDis:(NSString *)dis{
    self.province = province;
    self.city = city;
    self.dis = dis;
    self.selectCity.text = [city stringByAppendingString:dis];
    [self.selectBackView removeFromSuperview];
    [self.cityView removeFromSuperview];
}

#pragma mark - 点击选择城市弹出城市选择器
- (void)selectCityName{
    
    CityPicker *ciyPiker = [[[NSBundle mainBundle]loadNibNamed:@"cityPicker" owner:self options:nil]lastObject];
    
    UIView *selectView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height/2-ciyPiker.frame.size.height)];
    selectView.backgroundColor = [UIColor colorWithWhite:0 alpha:0.3];
    self.selectBackView = selectView;
    
    
    
    ciyPiker.delegate = self;
    
    CGRect rect = ciyPiker.frame;
    rect.origin.y = selectView.frame.size.height;
    rect.size.width = selectView.frame.size.width;
    ciyPiker.frame = rect;
    
    self.cityView = ciyPiker;
    
    [self addSubview:ciyPiker];
    [self addSubview:selectView];

    
}

#pragma makr - 解决键盘遮挡输入框问题,当输入是输入框上移
-(void)textFieldDidBeginEditing:(UITextField *)textField{

    CGRect frame                     = textField.frame;
    int offset                       = frame.origin.y + 70 - (self.frame.size.height - 216.0);//键盘高度216
    NSTimeInterval animationDuration = 0.30f;
    [UIView beginAnimations:@"ResizeForKeyBoard" context:nil];
    [UIView setAnimationDuration:animationDuration];
    float width                      = self.frame.size.width;
    float height                     = self.frame.size.height;
    if(offset > 0)
    {
        CGRect rect = CGRectMake(0.0f, -offset,width,height);
        self.frame  = rect;
    }
    [UIView commitAnimations];
}

#pragma mark - 当输入完毕是恢复输入之前的状态
-(void)textFieldDidEndEditing:(UITextField *)textField{
    self.frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
}

#pragma mark -关闭软键盘
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    [self endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - 点击获取验证码按钮进行验证手机号、发送验证码、时间倒计时
- (IBAction)getIdentityCode:(id)sender {
    
    AFHTTPRequestOperationManager *manager            = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer                         = [AFJSONRequestSerializer serializer];
    manager.responseSerializer                        = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    
    self.managers = manager;
    
    //验证手机号是否已被注册
    NSDictionary *isExistTelephone = @{@"serviceName":@"isExistTelephone",@"queryParameters":@{@"telephone":_phoneNum.text}};
        [manager POST:url parameters:isExistTelephone success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"JSON: %@", responseObject);
            NSString *comment = [responseObject valueForKey:@"comment"];
            NSString *status = [responseObject valueForKey:@"status"];
            if ([status isEqualToString:@"0"]) {
                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:comment delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
            }else{
                //进行时间倒计时，默认10秒
                __block int time = 10;
                dispatch_queue_t queue   = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
                dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);//每秒执行
                dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
                dispatch_source_set_event_handler(_timer, ^{
                    if (time==0) {// 当为0时关闭倒计时提示
                        dispatch_source_cancel(_timer);
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [_identityBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                            [_identityBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
                            
                            _identityBtn.userInteractionEnabled = YES;
                        });
                        
                    }else{
                        //            int minutes = timeout / 60;
                        int seconds = time % 60;
                        NSString *strTime = [NSString stringWithFormat:@"%d", seconds];
                        dispatch_async(dispatch_get_main_queue(), ^{
                            //设置界面的按钮显示 根据自己需求设置
                            //                NSLog(@"____%@",strTime);
                            [_identityBtn setTitle:[NSString stringWithFormat:@"%@秒后重新发送",strTime] forState:UIControlStateNormal];
                            [_identityBtn setTitleColor:[UIColor brownColor] forState:UIControlStateNormal];
                            _identityBtn.userInteractionEnabled = NO;
                        });
                        time--;
                        
                    }
                    
                });
                dispatch_resume(_timer);
                
                
                //发送短信获取验证码
                NSDictionary *sendSms = @{@"serviceName":@"sendSms",@"queryParameters":@{@"telephone":_phoneNum.text}};
                [manager POST:url parameters:sendSms success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    NSArray *value   = [responseObject valueForKey:@"dataList"];
                    NSString *random = [value valueForKey:@"randomCode"];
                    randomCode       = random;
                    NSLog(@"success%@",randomCode);
                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"error%@",error);
                }];
            }
    
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];
    
    
    
}

#pragma mark - 对输入框长度进行限制
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
//    validate *vali = [validate alloc];
    
    //限制手机号长度位11位
    if (_phoneNum == textField) {
        if (range.location>10) {
            return  NO;
        }
        
    }
    //验证码为6位
    if (_identityCode == textField) {
        if (range.location>5) {
            return NO;
        }
    }
    //密码6-20位
    if (_newsPsw == textField) {
        if (range.location>19) {
            return NO;
        }
    }
    
    return YES;
}

#pragma mark - 点击按钮进行文本框内容的验证
- (IBAction)commonRegister:(id)sender {
    ValidateHelper *validate = [[ValidateHelper alloc]init];
    BOOL flag =  [validate isMobileNumber:_phoneNum.text];
    if (!flag) {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"手机号格式不正确" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                [alert show];
                //清空文本框内容，并获得焦点
                _phoneNum.text = nil;
                [_phoneNum becomeFirstResponder];
    }else{
        if(![_identityCode.text isEqualToString:randomCode]) {
                        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"验证码输入不正确" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                        [alert show];
                        _identityCode.text = nil;
                        [_identityCode becomeFirstResponder];
                    }else{
                //密码格式
                        BOOL psw = [validate validatePsw:_newsPsw.text];

                        if (!psw) {
                            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"密码格式不正确" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                            [alert show];
                            _newsPsw.text      = nil;
                            [_newsPsw becomeFirstResponder];
                        }else{
                //密码是否一致
                            if (![_newsPsw.text isEqualToString:_confirmPsw.text]) {
                                UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:@"两次输入密码不一致" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                                [alert show];
                                _confirmPsw.text   = nil;
                                [_confirmPsw becomeFirstResponder];
                            }
                        }
                    }
    }
    
    AFHTTPRequestOperationManager *manager            = [AFHTTPRequestOperationManager manager];

    //申明返回的结果是json类型
    manager.responseSerializer                        = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer=[AFJSONRequestSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
    //提交的时候判断手机号是否存在
    NSDictionary *isExistTelephone                    = @{@"serviceName":@"isExistTelephone",@"queryParameters":@{@"telephone":_phoneNum.text}};
    [manager POST:url parameters:isExistTelephone success:^(AFHTTPRequestOperation *operation, id responseObject) {
        int status  = [[responseObject objectForKey:@"status"]intValue];
        NSString *comment = [responseObject valueForKey:@"comment"];
        if(status == 0){
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:nil message:comment delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alert show];
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    //注册保存到数据库
    NSDictionary *commonMemberRegister = @{@"serviceName":@"commonMemberRegister",@"queryParameters":@{@"telephone":_phoneNum.text,@"password":_newsPsw.text,@"province":self.province,@"city":self.city,@"area":self.dis}};
    [manager POST:url parameters:commonMemberRegister success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"JSON: %@", responseObject);
        NSString *value = [responseObject valueForKey:@"comment"];
        NSLog(@"%@",value);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

}

    

@end
